﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaPrice;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaPrice;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaPrice
{
    /// <summary>
    /// 报价信息服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev", Name = "ZyOaPrice", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaPriceService : IZyOaPriceService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaPriceEntity> _zyOaPriceRepository;
        private readonly ISqlSugarRepository<ZyOaPricelistEntity> _zyOaPricelistRepository;
        private readonly IDictionaryDataService _dictionaryDataService;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaPriceService"/>类型的新实例
        /// </summary>
        public ZyOaPriceService(
            ISqlSugarRepository<ZyOaPriceEntity> zyOaPriceRepository,
            ISqlSugarRepository<ZyOaPricelistEntity> zyOaPricelistRepository,
            IBillRullService billRuleService,
            IUserManager userManager,
            IDictionaryDataService dictionaryDataService)
        {
            _zyOaPriceRepository = zyOaPriceRepository;
            _db = _zyOaPriceRepository.Context;
            _zyOaPricelistRepository = zyOaPricelistRepository;
            _billRuleService = billRuleService;
            _userManager = userManager;
            _dictionaryDataService = dictionaryDataService;
        }

        /// <summary>
        /// 获取报价信息
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaPriceEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaPriceInfoOutput>();

            var zyOaPricelistList = await _db.Queryable<ZyOaPricelistEntity>().Where(w => w.PriceId == entity.Id).ToListAsync();
            output.zyOaPricelistList = zyOaPricelistList.Adapt<List<ZyOaPricelistInfoOutput>>();
            return output;
        }






        /// <summary>
		/// 获取报价信息列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> ZyOaPrice([FromQuery] ZyOaPriceListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            var data = await _db.Queryable<ZyOaPriceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.project), p => p.Project.Contains(input.project))
                .WhereIF(!string.IsNullOrEmpty(input.customer), p => p.Customer.Contains(input.customer))
                .Select(it => new
                {
                    id = it.Id,
                    enCode = it.EnCode,
                    customer = it.Customer,
                    creatorTime = it.CreatorTime,
                    creatorUserId = it.CreatorUserId,
                    remark = it.Remark,
                }).MergeTable().Select<ZyOaPriceListOutput>().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return TkPageResult<ZyOaPriceListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建报价信息
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaPriceCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaPriceEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.EnCode = await _billRuleService.GetBillNumber("ZYBJ");
            entity.CreatorTime = DateTime.Now;
            entity.CreatorUserId = _userManager.UserId;
            try
            {
                //开启事务
                _db.Ado.BeginTran();

                //新增报价信息记录
                var newEntity = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntityAsync();

                var zyOaPricelistEntityList = input.zyOaPricelistList.Adapt<List<ZyOaPricelistEntity>>();
                foreach (var item in zyOaPricelistEntityList)
                {
                    item.Id = YitIdHelper.NextId().ToString();
                    item.PriceId = newEntity.Id;
                }
                await _db.Insertable(zyOaPricelistEntityList).ExecuteCommandAsync();

                //关闭事务
                _db.Ado.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.Ado.RollbackTran();
                throw YNTKException.Oh(ErrorCode.COM1000);
            }
        }



        /// <summary>
        /// 获取报价信息无分页列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaPriceListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            var data = await _db.Queryable<ZyOaPriceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.project), p => p.Project.Contains(input.project))
                .WhereIF(!string.IsNullOrEmpty(input.customer), p => p.Customer.Contains(input.customer))
                .Select(it => new
                {
                    id = it.Id,
                    enCode = it.EnCode,
                    customer = it.Customer,
                    creatorTime = it.CreatorTime,
                    creatorUserId = it.CreatorUserId,
                    remark = it.Remark,
                }).MergeTable().Select<ZyOaPriceListOutput>().OrderBy(sidx + " " + input.sort).ToListAsync();
            return data;
        }




        /// <summary>
		/// 获取报价信息子表无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("GetPriceList/{id}")]
        public async Task<dynamic> GetPriceList(string id)
        {
            
            //var dislist = _dictionaryTypeService.GetList().Result;
            var data = await _db.Queryable<ZyOaPricelistEntity>()
                .WhereIF(!string.IsNullOrEmpty(id), p => p.PriceId.Contains(id))
                .Select(it => new
                {
                    id = it.Id,
                    name = it.Name,
                    specs = it.Specs,
                    Unit = it.Unit,
                    num = it.Num,
                    Amount = it.Amount,
                    description = it.Description,
                    sortCode = it.SortCode
                }).MergeTable().Select<ZyOaPricelistCrOutput>()
                .Mapper(output => {

                   // var u = output.unit;
                    output.unit = _dictionaryDataService.GetInfo(output.unit).Result.FullName;

                }).ToListAsync();
            return data;
        }




        /// <summary>
		/// 导出报价信息
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaPriceListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaPriceListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.ZyOaPrice(input));
                exportData = data.Solidify<TkPageResult<ZyOaPriceListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"自动编号\",\"field\":\"enCode\"},{\"value\":\"客户名称\",\"field\":\"customer\"},{\"value\":\"备注说明\",\"field\":\"remark\"},{\"value\":\"创建用户\",\"field\":\"creatorUserId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "报价信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaPriceListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 更新报价信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaPriceUpInput input)
        {
            var entity = input.Adapt<ZyOaPriceEntity>();
            entity.LastModifyTime = DateTime.Now;
            entity.LastModifyUserId = _userManager.UserId;
            try
            {
                //开启事务
                _db.Ado.BeginTran();

                //更新报价信息记录
                await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

                //清空原有数据
                await _db.Deleteable<ZyOaPricelistEntity>().Where(u => u.PriceId == id).ExecuteCommandAsync();
                //新增新数据
                var zyOaPricelistEntityList = input.zyOaPricelistList.Adapt<List<ZyOaPricelistEntity>>();
                zyOaPricelistEntityList.ForEach(t =>
                {
                    t.Id = YitIdHelper.NextId().ToString();
                    t.PriceId = entity.Id;
                });
                await _db.Insertable(zyOaPricelistEntityList).ExecuteCommandAsync();

                //关闭事务
                _db.Ado.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.Ado.RollbackTran();
                throw YNTKException.Oh(ErrorCode.COM1001);
            }
        }

        /// <summary>
        /// 删除报价信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaPriceEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            try
            {
                //开启事务
                _db.Ado.BeginTran();

                //删除报价信息记录
                await _db.Deleteable<ZyOaPriceEntity>().Where(d => d.Id == id).ExecuteCommandAsync();

                //清空子表数据
                await _db.Deleteable<ZyOaPricelistEntity>().Where(u => u.PriceId == id).ExecuteCommandAsync();

                //关闭事务
                _db.Ado.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.Ado.RollbackTran();
                throw YNTKException.Oh(ErrorCode.COM1002);
            }
        }
    }
}
